package start.spring.basic.util.common;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;

/**
 * 
 * ****************************************************************************
 * 服务器ip工具类
 *
 * @author(作者)：xuyongyun	
 * @date(创建日期)：2023年2月17日
 ******************************************************************************
 */
public class ServerIpUtil {
	
	/**
	 * 获取服务器ip
	 *	
	 * @return
	 * @throws UnknownHostException 
	 * @throws SocketException
	 * @since           1.0
	 */
	public static String getServerIp() throws UnknownHostException, SocketException {
		String ip = null;
		StringBuilder ipBuffer = new StringBuilder();
        
        Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces();
        // 遍历所有的网络接口
        while (ifaces.hasMoreElements()) {
            NetworkInterface iface = (NetworkInterface) ifaces.nextElement();
            Enumeration<InetAddress> inetAddrs = iface.getInetAddresses();
            // 在所有的接口下再遍历IP
            while(inetAddrs.hasMoreElements()) {
                InetAddress inetAddr = (InetAddress) inetAddrs.nextElement();
                if (!inetAddr.isLoopbackAddress()) {// 排除loopback类型地址
                    if (inetAddr.isSiteLocalAddress()) {
                    	ipBuffer.append(",");
                    	ipBuffer.append(inetAddr.getHostAddress());
                    }
                }
            }
        }
        
        // 如果没有发现 non-loopback地址
        if(ipBuffer.length()==0) {
        	InetAddress jdkSuppliedAddress = InetAddress.getLocalHost();
        	ipBuffer.append(",");
        	ipBuffer.append(jdkSuppliedAddress.getHostAddress());
        }
        
        ip = ipBuffer.toString();
        if(!StringUtil.isEmpty(ip)) {
        	ip = ip.substring(1);
        }
        
	    return ip;
	}
	
	/**
	 * 获取服务器hostname
	 *	
	 * @return
	 * @since           1.0
	 */
	public static String getHostName() {
		InetAddress addr = null;
		String hostName = "";
		try {
			addr = InetAddress.getLocalHost();
			if(addr!=null) {
				hostName = addr.getHostName().toString();
			}
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
        return hostName;
	}

}
